'use strict';
const UniID = require('uni-id-common');

exports.main = async (event, context) => {
  // 解析请求体
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return { 
        code: 400, 
        message: "请求体解析失败",
        error: e.message 
      };
    }
  }

  try {
    const db = uniCloud.database();
    const collection = db.collection('uni-id-users');

    // 初始化 uni-id 实例
    const uniID = UniID.createInstance({ context });

    // 查询条件
    const query = {
      is_consultant: 2,
      profileCompleted: true
    };

    // 分页参数
    const page = body.page || 1;
    const pageSize = body.pageSize || 10;
    const skip = (page - 1) * pageSize;

    // 查询用户列表
    const res = await collection
      .where(query)
      .field({
        _id: true,
        username: true,
        is_consultant: true,
        register_date: true
      })
      .skip(skip)
      .limit(pageSize)
      .get();

    const countRes = await collection.where(query).count();

    const consultantIds = res.data.map(item => item._id);

    const supervisorRes = await db.collection('consultants')
      .where({
        user_id: db.command.in(consultantIds)
      })
      .get();

    // 为每个项生成 token
    const supervisorsWithToken = await Promise.all(supervisorRes.data.map(async item => {
      const tokenRes = await uniID.createToken({
        uid: item.user_id,
        needPermission: false
      });

      return {
        ...item,
        token: tokenRes.token
      };
    }));

    return {
      code: 200,
      message: "获取督导列表成功",
      data: {
        list: supervisorsWithToken,
        total: countRes.total,
        page,
        pageSize,
        totalPages: Math.ceil(countRes.total / pageSize)
      }
    };

  } catch (error) {
    console.error('获取督导列表失败:', error);
    return {
      code: 500,
      message: "服务器内部错误",
      error: error.message
    };
  }
};
